// #include "Shared.h"
#include "Shaders/utility.hlsl"

// #define CUBE_SKYBOX

ConstantBuffer<Constants> constant : register(b0);

#ifdef CUBE_SKYBOX
TextureCube radianceIBLTexture : register(t0);
#else
Texture2D<float3> radianceIBLTexture : register(t0);
#endif

SamplerState defaultSampler : register(s0);

struct VSInput
{
    float3 position : POSITION;
};

struct VSOutput
{
    float4 position : SV_POSITION;
    float3 viewDir : TEXCOORD;
};

float3 DecodeRGBE8(float4 rgbe)
{
    float exponent = rgbe.a * 255.0f - 128.0f - 8.0f;
    return rgbe.rgb * exp2(exponent);
}

float3 MultiplyExposure(float3 rgbe)
{
    return rgbe.rgb * exp2(constant.ExposureKd.x);
}

VSOutput VSMain(uint VertID: SV_VertexID)
{
    float2 ScreenUV = float2(uint2(VertID, VertID << 1) & 2);
    float4 ProjectedPos = float4(lerp(float2(-1, 1), float2(1, -1), ScreenUV), 1, 1);

    VSOutput output;
    output.position = ProjectedPos;
    float4 worldH = mul(constant.InvViewProj, ProjectedPos);
    output.viewDir = worldH.xyz / worldH.w;

    return output;
}

float4 PSMain(VSOutput input) : SV_TARGET
{
#ifdef CUBE_SKYBOX
    return float4(radianceIBLTexture.SampleLevel(defaultSampler, input.viewDir, 0));
#else
    float2 uv = SampleSphericalMap(input.viewDir);
    float3 rgb = radianceIBLTexture.Sample(defaultSampler, uv);
    return float4(MultiplyExposure(rgb), 1);

#endif
    // return float4(input.viewDir, 1);
    // return float4(input.position.x / 1280, input.position.y / 720, 1, 1);
}
